package authorization_code_postgres

import (
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var db *gorm.DB

func initDB() {
	// 配置 PostgreSQL 连接
	dsn := "host=192.168.20.5 user=postgres password=root dbname=oauth port=5432 sslmode=disable TimeZone=UTC"
	// 配置GORM
	config := &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	}
	var err error
	// 连接数据库
	db, err = gorm.Open(postgres.Open(dsn), config)
	if err != nil {
		panic(err)
	}
	// 自动迁移表结构
	if err := db.AutoMigrate(&User{}, &Client{}, &Token{}); err != nil {
		panic(err)
	}
	// 插入测试数据
	var count int64
	db.Model(&Client{}).Count(&count)
	if count == 0 {
		// 创建测试用户
		user := User{
			Username: "testuser",
			Password: "password123", // 实际应用中应该哈希处理
			Email:    "test@example.com",
		}
		db.Create(&user)
		// 创建测试客户端
		client := Client{
			ID:     "client1",
			Secret: "secret1",
			Domain: "http://192.168.20.4:9094",
			UserID: user.ID,
		}
		db.Create(&client)
	}
}
